package com.desmond.parallaxheaderviewpager;

import haitao.puzzle.R;
import hiatao.puzzle.activity.FollowActivity;
import hiatao.puzzle.activity.SixinActivity;
import hiatao.puzzle.config.MyApplication;
import hiatao.puzzle.entity.User;
import hiatao.puzzle.utils.ImageUtils;
import hiatao.puzzle.utils.PixelUtil;
import hiatao.puzzle.utils.StatusBarCompat;
import hiatao.puzzle.utils.Tools;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;


public class TestActivity extends FragmentActivity implements ScrollTabHolder ,OnClickListener{

    public static final String TAG = TestActivity.class.getSimpleName();

    private static final String IMAGE_TRANSLATION_Y = "image_translation_y";
    private static final String HEADER_TRANSLATION_Y = "header_translation_y";

    private ViewPager mViewPager;
    private View mHeader;
    private ImageView mTopImage;
    private ViewPagerAdapter mAdapter;

    private int mMinHeaderHeight;
    private int mHeaderHeight;
    private int mMinHeaderTranslation;
    private int mNumFragments;

    private int mScrollState;
    private ListViewFragment fragment;
    private ListViewFragment1 fragment1;
    private ListViewFragment2 fragment2;
    
    private View top_back;
	private View btn_more;
	//private TextView sixin_tv;
	private TextView title_tv;
	private TextView intro_tv;
	private View follow_tv;
	private View sixin_tv;
	private TextView myfollow_tv;
	private TextView fans_tv;
	private TextView zuan_tv;
	private TextView original_tv;
	private TextView like_tv;
	private ImageView head_img;
	private LinearLayout ly1;
	private LinearLayout ly2;
	private LinearLayout ly3;

	private LinearLayout layout[];
	int index = 0;
	private boolean self;
	private User user;
	private View pop_view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        initValues();

        mTopImage = (ImageView) findViewById(R.id.image);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mHeader = findViewById(R.id.header);

        if (savedInstanceState != null) {
            mTopImage.setTranslationY(savedInstanceState.getFloat(IMAGE_TRANSLATION_Y));
            mHeader.setTranslationY(savedInstanceState.getFloat(HEADER_TRANSLATION_Y));
        }
        StatusBarCompat.compat(this, getResources().getColor(R.color.primary));
        setupAdapter();
    }

    private void initValues() {
        int tabHeight = getResources().getDimensionPixelSize(R.dimen.tab_height);
        mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
        mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
        mMinHeaderTranslation = -mMinHeaderHeight + tabHeight+(PixelUtil.dp2px(this, 50)-tabHeight);

        mNumFragments = 3;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putFloat(IMAGE_TRANSLATION_Y, mTopImage.getTranslationY());
        outState.putFloat(HEADER_TRANSLATION_Y, mHeader.getTranslationY());
        super.onSaveInstanceState(outState);
    }

    private void setupAdapter() {
    	
    	
		 self = getIntent().getBooleanExtra("SELF", true);
		 user = (User) getIntent().getSerializableExtra("USER");
		 
		 if(!self){
			
		 }else{
			 user= MyApplication.getInstance().user;
		 }
		 top_back =  findViewById(R.id.top_back);
		 btn_more = findViewById(R.id.btn_more);
		 title_tv = (TextView) findViewById(R.id.title);
		 
		 
		 head_img = (ImageView) findViewById(R.id.head_image);
		 intro_tv = (TextView)findViewById(R.id.intro_tv);
		 zuan_tv = (TextView)  findViewById(R.id.zuan_tv);
		 myfollow_tv = (TextView) findViewById(R.id.myfollow_tv);
		 fans_tv = (TextView) findViewById(R.id.fans_tv);
		 original_tv = (TextView) findViewById(R.id.original_tv);
		 like_tv = (TextView) findViewById(R.id.like_tv);
		 myfollow_tv.setText("关注 "+Tools.getRandom(8, 300));
		 fans_tv.setText("粉丝 "+Tools.getRandom(8, 300));
		 original_tv.setText(""+Tools.getRandom(2, 60));
		 like_tv.setText(""+Tools.getRandom(1, 100));

		 if(!self){
			 btn_more.setVisibility(View.VISIBLE);
			 title_tv.setText(user.getName());
			 intro_tv.setText("简介："+user.getIntro());
			 zuan_tv.setText(""+user.getZuanNum());
			 ImageUtils.loadImg(user.getHeadUrl(), head_img);
			 
		 }else{
			 title_tv.setText(MyApplication.getInstance().user.getName());
			 ImageUtils.loadImg(MyApplication.getInstance().user.getHeadUrl(), head_img);
		 }
		 
		 top_back.setOnClickListener(new OnClickListener() {
				
			@Override
			public void onClick(View v) {
				 TestActivity.this.finish();
			}
		});
		 myfollow_tv.setOnClickListener(new OnClickListener() {
			 
			 @Override
			 public void onClick(View v) {
				 
				 String title = "关注";
				 if(!self){
					 title=user.getName()+"的关注";
				 }
				 Tools.goActivity(TestActivity.this, FollowActivity.class, new String[]{"TITLE"}, new String[]{title});
			 }
		 });
		 fans_tv.setOnClickListener(new OnClickListener() {
			 
			 @Override
			 public void onClick(View v) {
				 String title = "粉丝";
				 if(!self){
					 title=user.getName()+"的粉丝";
				 }
				 Tools.goActivity(TestActivity.this, FollowActivity.class, new String[]{"TITLE"}, new String[]{title});
			 }
		 });
		 
		 
		 
		 
		 //
		 pop_view = getLayoutInflater().inflate(R.layout.share_popup_window, null);
		 btn_more.setOnClickListener(new OnClickListener() {
			 @Override
			 public void onClick(View v) {
				 showPpw();
			 }
			 
		 });
		 
		 
		 fragment  =  new ListViewFragment(0,user);
    	fragment1 = new ListViewFragment1(1,user);
    	fragment2 = new ListViewFragment2(2,user);
        if (mAdapter == null) {
            mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mNumFragments);
        }

        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(mNumFragments);
        mViewPager.setOnPageChangeListener(getViewPagerPageChangeListener());
        
		 ly1 =  (LinearLayout) findViewById(R.id.ly1);
		 ly2 =  (LinearLayout) findViewById(R.id.ly2);
		 ly3 =  (LinearLayout) findViewById(R.id.ly3);
		 layout = new LinearLayout[]{ly1,ly2,ly3};
		 ly1.setOnClickListener(this);
		 ly2.setOnClickListener(this);
		 ly3.setOnClickListener(this);
    }
    private void showPpw(){
		
		final PopupWindow popupWindow = new PopupWindow(pop_view,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(true);
		// 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
		// 我觉得这里是API的一个bug
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置好参数之后再show
		popupWindow.showAsDropDown(btn_more, 0, 0);
		 follow_tv = pop_view.findViewById(R.id.follow_view);
		 sixin_tv = pop_view.findViewById(R.id.sixin_view);
		 follow_tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!MyApplication.getInstance().isLogin) {
					Tools.showToast("请先登陆!");
				} else {
					Tools.showToast("已关注");
					//follow_tv.setText("已关注");
					//follow_tv.setBackgroundResource(R.drawable.btn_follow_press);
				}
				popupWindow.dismiss();
			}
			
		});
		 sixin_tv.setOnClickListener(new OnClickListener() {
			 @Override
			 public void onClick(View v) {
				 // TODO Auto-generated method stub
				 if (!MyApplication.getInstance().isLogin) {
					 Tools.showToast("请先登陆!");
				 } else {
					Intent intent = new Intent(TestActivity.this, SixinActivity.class);
					intent.putExtra("USER", user);
					TestActivity.this.startActivity(intent);
				 }
				 popupWindow.dismiss();
			 }
			 
		 });
	}
    private ViewPager.OnPageChangeListener getViewPagerPageChangeListener () {
        ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                int currentItem = mViewPager.getCurrentItem();
                if (positionOffsetPixels > 0) {
                    SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mAdapter.getScrollTabHolders();

                    ScrollTabHolder fragmentContent;
                    if (position < currentItem) {
                        // Revealed the previous page
                        fragmentContent = scrollTabHolders.valueAt(position);
                    } else {
                        // Revealed the next page
                        fragmentContent = scrollTabHolders.valueAt(position + 1);
                    }

                    fragmentContent.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()),
                            mHeader.getHeight());
                }
            }

            @Override
            public void onPageSelected(int position) {
            	setSelcet(position);
                SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mAdapter.getScrollTabHolders();

                if (scrollTabHolders == null || scrollTabHolders.size() != mNumFragments) {
                    return;
                }

                ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position);
                currentHolder.adjustScroll(
                        (int) (mHeader.getHeight() + mHeader.getTranslationY()),
                        mHeader.getHeight());
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                mScrollState = state;
            }
        };

        return listener;
    }

    @Override
    public void adjustScroll(int scrollHeight, int headerTranslationY) {}

    @Override
    public void onListViewScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount, int pagePosition) {
        if (mViewPager.getCurrentItem() == pagePosition) {
            scrollHeader(getScrollY(view));
        }
    }

    @Override
    public void onScrollViewScroll(ScrollView view, int x, int y, int oldX, int oldY, int pagePosition) {
        if (mViewPager.getCurrentItem() == pagePosition){
            scrollHeader(view.getScrollY());
        }
    }

    private void scrollHeader(int scrollY) {
        float translationY = Math.max(-scrollY, mMinHeaderTranslation);
        mHeader.setTranslationY(translationY);
        mTopImage.setTranslationY(-translationY / 3);
    }

    private int getScrollY(AbsListView view) {
        View child = view.getChildAt(0);
        if (child == null) {
            return 0;
        }

        int firstVisiblePosition = view.getFirstVisiblePosition();
        int top = child.getTop();

        int headerHeight = 0;
        if (firstVisiblePosition >= 1) {
            headerHeight = mHeaderHeight;
        }

        return -top + firstVisiblePosition * child.getHeight() + headerHeight;
    }


    private  class ViewPagerAdapter extends FragmentPagerAdapter {

        private SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
        private int mNumFragments;

        public ViewPagerAdapter(FragmentManager fm, int numFragments) {
            super(fm);
            mScrollTabHolders = new SparseArrayCompat<ScrollTabHolder>();
            mNumFragments = numFragments;
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fr;
            switch (position) {
                case 0:
                	fr =fragment;
                	
                    break;
                case 1:
                	fr =fragment1;
                	break;
                case 2:
                	fr =fragment2;
                	break;

                default:
                    throw new IllegalArgumentException("Wrong page given " + position);
            }
            return fr;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Object object = super.instantiateItem(container, position);

            mScrollTabHolders.put(position, (ScrollTabHolder) object);

            return object;
        }

        @Override
        public int getCount() {
            return mNumFragments;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "ScrollView";

                case 1:
                    return "ScrollView";

                case 2:
                    return "ListView";

                default:
                    throw new IllegalArgumentException("wrong position for the fragment in vehicle page");
            }
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
            return mScrollTabHolders;
        }
    }


	@Override
	public void onClick(View v) {
		
		int x =0;
		switch (v.getId()) {
		case R.id.ly1:
			x=0;
			break;
		case R.id.ly2:
			x=1;
			break;
		case R.id.ly3:
			x=2;
			break;

		default:
			break;
		}
		if(index !=x){
			//setSelcet(x);
			mViewPager.setCurrentItem(x);
		}
	}
	private void setSelcet(int x){
		TextView t0=(TextView) layout[x].getChildAt(0);
		TextView t1=(TextView) layout[x].getChildAt(1);
		t0.setTextColor(getResources().getColor(R.color.head_color));
		t1.setTextColor(getResources().getColor(R.color.head_color));
		t0=(TextView) layout[index].getChildAt(0);
		t1=(TextView) layout[index].getChildAt(1);
		t0.setTextColor(getResources().getColor(R.color.tab_nor));
		t1.setTextColor(getResources().getColor(R.color.tab_nor));
		index =x;
	}
}
